<?php 
class DBAccess 
{
    private $conn;
    private $db;
    private $u;
    private $p;
    
    public function __construct($db,$user,$pass){
        $this->db = $db;
        $this->u = $user;
        $this->p = $pass;
    }

    public function connect(){
        $this->conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$this->db",$this->u,$this->p); 
    }

    public function disconnect(){ @odbc_close($this->conn); }

    public function is_connected(){ return ($this->conn && $this->select_one("select 1")) ? true : false; }

    public function has_internet(){ 
        //check to see if the local machine is connected to the web 
        //uses sockets to open a connection to apisonline.com 
        $url = parse_url(SMS_URL);
        $port = ($url['port']) ?$url['port'] : 80;
        $host = ($url['host']) ?$url['host'] : 'localhost'; 
        $connected = @fsockopen("tcp://{$host}",$port, $errno, $errstr, 10);
        if ($connected){ 
            fclose($connected); 
            return true;
        }
        return false; 
    }
        
    public function select_all($sql){
        $rs=odbc_exec($this->conn,$sql);
        $result = Array();
        while ($res=odbc_fetch_array($rs)) { 
            $result[]=$res;
        }
        return $result;
    }

    public function select_one($sql){
        $rs=odbc_exec($this->conn,$sql);
        return odbc_result($rs,1); 
    }
    public function send_sms($stud_no,$e_date,$e_time,$e_mode=0){
        $url = SMS_URL . '&stud_no=' . urlencode($stud_no) . '&e_date=' . urlencode($e_date) . '&e_time=' . urlencode($e_time) . "&e_mode=$e_mode";
        return $this->call_url($url); 
    }
    private function call_url($url){
        $sock = @fopen($url,'r');
        if ($sock){ 
            $str = fread($sock, 4096);
            fclose($sock); 
            return $str;
        }
        return;

        $ch = curl_init ($url);
        ob_start();
        curl_exec($ch);
        $str = ob_get_contents();
        ob_end_clean();
        curl_close ($ch);        
        return $str;
    }

    public function get_student($date = false, $time=false){
        $date = ($date) ? $date : date("Ymd");
        $time = ($time) ? $time : "060000"; #date("His");
        $sql="SELECT e_date,e_time, e_id,e_name,idno,e_mode from tenter 
              LEFT JOIN tuser ON tuser.id = tenter.e_id
              WHERE e_date = '$date' and e_time > '$time';";
        return $this->select_all($sql);
    }

    public function get_config(){
        if ($this->has_internet()) {
            $res = $this->call_url(SMS_URL . '&get_config=true');
        }else{
            $res = "";
        }
        return (empty($res)) ? "" : $res; 
    }

}
?>
